<!--
  分账规则管理主页面
  @description 分账规则管理的列表页面，包含搜索、表格、分页、操作等功能
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <ContentWrap>
    <!-- 搜索表单 -->
    <el-form
      ref="queryFormRef"
      :model="queryParams"
      :inline="true"
      label-width="68px"
      class="-mb-15px"
    >
      <el-form-item :label="t('settle.splitRule.ruleName')" prop="ruleName">
        <el-input
          v-model="queryParams.ruleName"
          :placeholder="t('settle.common.pleaseInput') + t('settle.splitRule.ruleName')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('settle.splitRule.merchantNo')" prop="merchantNo">
        <el-input
          v-model="queryParams.merchantNo"
          :placeholder="t('settle.common.pleaseInput') + t('settle.splitRule.merchantNo')"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item :label="t('settle.splitRule.ruleType')" prop="ruleType">
        <el-select
          v-model="queryParams.ruleType"
          :placeholder="t('settle.common.pleaseSelect') + t('settle.splitRule.ruleType')"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="(label, value) in ruleTypeOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('settle.common.status')" prop="status">
        <el-select
          v-model="queryParams.status"
          :placeholder="t('settle.common.pleaseSelect') + t('settle.common.status')"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="(label, value) in statusOptions"
            :key="value"
            :label="label"
            :value="parseInt(value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('settle.common.createTime')" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          type="datetimerange"
          range-separator="-"
          :start-placeholder="t('settle.common.startTime')"
          :end-placeholder="t('settle.common.endTime')"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          {{ t('settle.common.search') }}
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          {{ t('settle.common.reset') }}
        </el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['settle:split-rule:create']"
        >
          <Icon class="mr-5px" icon="ep:plus" />
          {{ t('settle.common.add') }}
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['settle:split-rule:export']"
        >
          <Icon class="mr-5px" icon="ep:download" />
          {{ t('settle.common.export') }}
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" row-key="id">
      <el-table-column :label="t('settle.splitRule.ruleName')" align="center" prop="ruleName" min-width="150" />
      <el-table-column :label="t('settle.splitRule.merchantNo')" align="center" prop="merchantNo" width="180" />
      <el-table-column :label="t('settle.splitRule.merchantName')" align="center" prop="merchantName" min-width="150" />
      <el-table-column :label="t('settle.splitRule.ruleType')" align="center" prop="ruleType" width="120">
        <template #default="scope">
          <el-tag :type="getRuleTypeTagType(scope.row.ruleType)">
            {{ ruleTypeOptions[scope.row.ruleType] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="t('settle.splitRule.splitRatio')" align="center" prop="splitRatio" width="100">
        <template #default="scope">
          <span v-if="scope.row.ruleType === SplitRuleTypeEnum.RATIO">
            {{ scope.row.splitRatio }}%
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('settle.splitRule.splitAmount')" align="center" prop="splitAmount" width="120">
        <template #default="scope">
          <span v-if="scope.row.ruleType === SplitRuleTypeEnum.AMOUNT">
            ¥{{ (scope.row.splitAmount / 100).toFixed(2) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column :label="t('settle.common.status')" align="center" prop="status" width="100">
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ statusOptions[scope.row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        :label="t('settle.common.createTime')"
        align="center"
        prop="createTime"
        width="180"
        :formatter="dateFormatter"
      />
      <el-table-column :label="t('settle.common.operation')" align="center" width="240" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['settle:split-rule:update']"
          >
            {{ t('settle.common.edit') }}
          </el-button>
          <el-button
            link
            type="success"
            @click="handleEnable(scope.row)"
            v-hasPermi="['settle:split-rule:update']"
            v-if="scope.row.status === SplitRuleStatusEnum.DISABLED"
          >
            {{ t('settle.splitRule.enable') }}
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleDisable(scope.row)"
            v-hasPermi="['settle:split-rule:update']"
            v-if="scope.row.status === SplitRuleStatusEnum.ENABLED"
          >
            {{ t('settle.splitRule.disable') }}
          </el-button>
          <el-button
            link
            type="info"
            @click="openRecordList(scope.row)"
            v-hasPermi="['settle:split-rule:query']"
          >
            {{ t('settle.splitRule.viewRecords') }}
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['settle:split-rule:delete']"
          >
            {{ t('settle.common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <SplitRuleForm ref="formRef" @success="getList" />
  
  <!-- 分账记录列表 -->
  <SplitRecordList ref="recordListRef" />
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { dateFormatter } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import { 
  getSplitRulePageApi, 
  deleteSplitRuleApi, 
  enableSplitRuleApi,
  disableSplitRuleApi,
  exportSplitRuleApi
} from '@/api/settle/splitRule'
import type { SplitRuleVO, SplitRulePageReqVO } from '@/api/settle/types'
import { SplitRuleTypeEnum, SplitRuleStatusEnum } from '@/api/settle/types'
import { ContentWrap } from '@/components/ContentWrap'
import { Icon } from '@/components/Icon'
import Pagination from '@/components/Pagination/index.vue'
import SplitRuleForm from './SplitRuleForm.vue'
import SplitRecordList from './SplitRecordList.vue'

defineOptions({ name: 'SettleSplitRule' })

const { t } = useI18n()
const message = useMessage()

// 加载状态
const loading = ref(true)
const exportLoading = ref(false)

// 列表数据
const list = ref<SplitRuleVO[]>([])
const total = ref(0)

// 查询参数
const queryParams = reactive<SplitRulePageReqVO>({
  pageNo: 1,
  pageSize: 10,
  ruleName: undefined,
  merchantNo: undefined,
  ruleType: undefined,
  status: undefined,
  createTime: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()
const formRef = ref()
const recordListRef = ref()

// 选项数据
const ruleTypeOptions = {
  [SplitRuleTypeEnum.RATIO]: t('settle.splitRule.ruleTypes.ratio'),
  [SplitRuleTypeEnum.AMOUNT]: t('settle.splitRule.ruleTypes.amount')
}

const statusOptions = {
  [SplitRuleStatusEnum.ENABLED]: t('settle.splitRule.statuses.enabled'),
  [SplitRuleStatusEnum.DISABLED]: t('settle.splitRule.statuses.disabled')
}

/**
 * 查询列表
 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getSplitRulePageApi(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('查询分账规则列表失败:', error)
  } finally {
    loading.value = false
  }
}

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/**
 * 新增/修改操作
 */
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/**
 * 删除按钮操作
 */
const handleDelete = async (id: number) => {
  try {
    await message.delConfirm()
    await deleteSplitRuleApi(id)
    message.success(t('settle.splitRule.tips.deleteSuccess'))
    await getList()
  } catch (error) {
    console.error('删除分账规则失败:', error)
  }
}

/**
 * 启用分账规则
 */
const handleEnable = async (row: SplitRuleVO) => {
  try {
    await ElMessageBox.confirm(
      t('settle.splitRule.tips.enableConfirm'),
      t('settle.common.confirmTitle'),
      {
        confirmButtonText: t('settle.common.confirm'),
        cancelButtonText: t('settle.common.cancel'),
        type: 'warning'
      }
    )
    
    await enableSplitRuleApi(row.id)
    ElMessage.success(t('settle.splitRule.tips.enableSuccess'))
    await getList()
  } catch (error) {
    console.error('启用分账规则失败:', error)
  }
}

/**
 * 禁用分账规则
 */
const handleDisable = async (row: SplitRuleVO) => {
  try {
    await ElMessageBox.confirm(
      t('settle.splitRule.tips.disableConfirm'),
      t('settle.common.confirmTitle'),
      {
        confirmButtonText: t('settle.common.confirm'),
        cancelButtonText: t('settle.common.cancel'),
        type: 'warning'
      }
    )
    
    await disableSplitRuleApi(row.id)
    ElMessage.success(t('settle.splitRule.tips.disableSuccess'))
    await getList()
  } catch (error) {
    console.error('禁用分账规则失败:', error)
  }
}

/**
 * 查看分账记录
 */
const openRecordList = (row: SplitRuleVO) => {
  recordListRef.value.open(row)
}

/**
 * 导出按钮操作
 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    await exportSplitRuleApi(queryParams)
    message.success(t('settle.common.exportSuccess'))
  } catch (error) {
    console.error('导出分账规则数据失败:', error)
  } finally {
    exportLoading.value = false
  }
}

// 标签类型获取函数
const getRuleTypeTagType = (type: number) => {
  const typeMap = {
    [SplitRuleTypeEnum.RATIO]: 'primary',
    [SplitRuleTypeEnum.AMOUNT]: 'success'
  }
  return typeMap[type] || ''
}

const getStatusTagType = (status: number) => {
  const statusMap = {
    [SplitRuleStatusEnum.ENABLED]: 'success',
    [SplitRuleStatusEnum.DISABLED]: 'info'
  }
  return statusMap[status] || ''
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>
